var params = {}, tableIns, $;
layui.use(['table','layer','jquery','element','sidebar','form','formSelects','laydate'], function(){
    $ = jQuery = layui.$;
    var table = layui.table;
    var layer = layui.layer;
    var element = layui.element;
    var sidebar = layui.sidebar;
    var form = layui.form;
    var formSelects = layui.formSelects;
    var laydate = layui.laydate;
    $.ajax({
        type: "POST",
        url: ctx+'/sys_admin/mineservice/showSearchs',
        data: {'moduleid':moduleid},
        async:false,
        success: function(data){
            $.each(data, function(i, column){
                var type = column.column_type;
                if (type == 'select') {
                    var options = '';
                    $.ajax({
                        type: "POST",
                        url: ctx+'/sys_admin/mineservice/getSelectData?foreignTable='+column.foreignTable+"&foreignKey="+column.foreignKey,
                        data: {'moduleid': moduleid},
                        async: false,
                        success: function (ops) {
                            $.each(ops, function(i, option){
                                options += '<option value="'+option.value+'">'+option.name+'</option>';
                            });
                        }
                    });
                    $('#searchForm').append('<div class="layui-input-inline" style="top: 3px;">' +
                        '       <select name="'+column.column_name+'" lay-filter="'+column.column_name+'" lay-search="">' +
                        '                    <option value="">选择'+column.column_comment+'</option>' +
                        options +
                        '                </select>' +
                        '       </div>');
                    form.on('select('+column.column_name+')', function(data){
                        $('#submitid').click();
                    });
                    /*formSelects.data(column.column_name, 'server', {
                        url: ctx+'/sys_admin/mineservice/getSelectData?foreignTable='+column.foreignTable,
                        success: function(id, url, searchVal, result){

                        }
                    });
                    formSelects.on(column.column_name, function(id, vals, val, isAdd, isDisabled){
                        if(isAdd){
                            formSelects.value(column.column_name, [val.id], true);
                        }else{
                            formSelects.value(column.column_name, []);
                        }
                        $('#submitid').click();
                    });*/
                } else if (type == 'yesorno') {
                    $('#searchForm').append('<div class="layui-input-inline" style="top: 3px;">' +
                        '                <select id="'+column.column_name+'id" name="'+column.column_name+'" lay-filter="'+column.column_name+'">' +
                        '                    <option value="">'+column.column_comment+'</option>' +
                        '                    <option value="1">是</option>' +
                        '                    <option value="2">否</option>' +
                        '                </select>' +
                        '            </div>');
                    form.on('select('+column.column_name+')', function(data){
                        $('#submitid').click();
                    });
                } else if (type == 'haveorno') {
                    $('#searchForm').append('<div class="layui-input-inline" style="top: 3px;">' +
                        '                <select id="'+column.column_name+'id" name="'+column.column_name+'" lay-filter="'+column.column_name+'">' +
                        '                    <option value="">'+column.column_comment+'</option>' +
                        '                    <option value="1">有</option>' +
                        '                    <option value="2">无</option>' +
                        '                </select>' +
                        '            </div>');
                    form.on('select('+column.column_name+')', function(data){
                        $('#submitid').click();
                    });
                } else if (type == 'sex') {
                    $('#searchForm').append('<div class="layui-input-inline" style="top: 3px;">' +
                        '                <select id="'+column.column_name+'id" name="'+column.column_name+'" lay-filter="'+column.column_name+'">' +
                        '                    <option value="">'+column.column_comment+'</option>' +
                        '                    <option value="1">男</option>' +
                        '                    <option value="2">女</option>' +
                        '                </select>' +
                        '            </div>');
                    form.on('select('+column.column_name+')', function(data){
                        $('#submitid').click();
                    });
                } else if (type == 'date' || type == 'datetime') {
                    $('#searchForm').append('<div class="layui-input-inline" style="top: 3px;width:220px">' +
                        '       <input type="search" name="'+column.column_name+'" autocomplete="off" class="layui-input dateruange" style="width:220px;" placeholder="'+column.column_comment+'范围"/>' +
                        '       </div>');
                } else {
                    $('#searchForm').append('<div class="layui-input-inline" style="top: 3px;">' +
                        '       <input type="search" name="'+column.column_name+'" autocomplete="off" class="layui-input" style="width:190px;" placeholder="'+column.column_comment+'"/>' +
                        '       </div>');
                }
            });
            $('#searchForm').append('<div class="layui-input-inline" style="top: 3px;">' +
                '<select name="createuser" xm-select="createUser" lay-verify=""  xm-select-radio xm-select-search  >' +
                ' <option value="">选择创建人</option>' +
                '</select>' +
                ' </div>');
            $('#searchForm').append('<div class="layui-input-inline" style="top: 3px;">' +
                '        <input type="text" name="createdate" class="layui-input" id="createdate" placeholder="创建日期">'+
                ' </div>');
            $('#searchForm').append('<div class="layui-input-inline">' +
                '       <button class="layui-btn" id="submitid" lay-submit lay-filter="serach_form" ><i class="layui-icon">&#xe615;</i> 查询</button>' +
                '       <button id="submitid" lay-submit lay-filter="serach_form" ></button>' +
                '       </div>');
            form.render();

        }
    });
    layui.formSelects.on('createUser',function(id, vals, val, isAdd, isDisabled){
        if(isAdd){
            formSelects.value('createUser', [val.id]);
        }else{
            formSelects.value('createUser', []);
        }
        $('#submitid').click();
    })
    lay('.dateruange').each(function(){
        laydate.render({
            elem: this,
            trigger: 'click',
            theme: 'grid',
            range: true,
            done: function(value, date){ //监听日期被切换
            }
        });
    });
    laydate.render({
        elem: '#createdate',
        trigger: 'click',
        theme: 'grid',
        range: true,
    });
    formSelects.data('createUser', 'server', {
        url: ctx+'/sys_admin/sys/user/getUserAll',
        keyword: 'name',
        keyVal: 'id',
    });
    tableIns = table.render({
        elem: '#modulestable',
        height:'full-113',
        size:'sm',
        url: ctx+'/sys_admin/mineservice/getPaginateList',
        where: {'moduleurl': moduleurl},
        page: true,
        even: true,
        totalRow: true,
        cols: [getFields()],
        done:function(res, curr){
            params['curr'] = curr;
        }
    });
    table.on('tool(modules)', function(obj){
        var data = obj.data;
        if(obj.event === 'del'){
            if(data.createuser!=userid){
                layer.open({
                    skin:'layui-layer-success',
                    title:'提示',
                    content:'非本人数据不能操作！',
                });
                return ;
            }
            layer.confirm('确定删除行么？', function(index){
                $.post(ctx+'/sys_admin/mineservice/delete', {"tablename":tablename, "ids":data.id}, function(result) {
                    if (result.success) {
                        layer.open({
                            skin:'layui-layer-success',
                            title:'提示',
                            content:'删除成功！',
                            yes:function(idx, layero){
                                tableIns.reload({});
                                layer.close(index);
                                layer.close(idx);
                            }
                        });
                        //obj.del();
                    } else {
                        layer.msg(result.msg);
                    }
                }, 'json');
            });
        } else if(obj.event === 'edit'){
            layer.open({
                title:"编辑",
                type: 2,
                area: ['80%', '80%'],
                fixed: false, //不固定
                maxmin: true,
                content: ctx+'/sys_admin/mineservice/form?tablename='+tablename+'&moduleid='+moduleid+'&id='+data.id,
                btn: ['保存','接口同步', '关闭'],
                yes: function(index, layero){
                    var iframeWin = layero.find('iframe')[0];
                    iframeWin.contentWindow.table = tableIns;
                    iframeWin.contentWindow.params = params;
                    layero.find('iframe').contents().find('#submit-btn').click();
                },
                btn2: function(index, layero){
                    var iframeWin = layero.find('iframe')[0];
                    iframeWin.contentWindow.table = tableIns;
                    layero.find('iframe').contents().find('#interface').click();
                    return false;
                },
                btn3: function(index, layero){
                    var index = layer.getFrameIndex(window.name);
                    layer.close(index);
                }
            });
        } else if(obj.event === 'detail'){
            layer.open({
                title:"编辑",
                type: 2,
                area: ['80%', '80%'],
                fixed: false, //不固定
                maxmin: true,
                content: ctx+'/sys_admin/mineservice/form?tablename='+tablename+'&moduleid='+moduleid+'&id='+data.id+'&type=1',
                btn: [ '关闭'],
                btn3: function(index, layero){
                    var index = layer.getFrameIndex(window.name);
                    layer.close(index);
                }
            });
        } else if(obj.event === 'attach'){
            layer.open({
                title:"附件管理",
                type: 2,
                area: ['80%', '80%'],
                fixed: false, //不固定
                maxmin: true,
                content: ctx+'/sys_admin/mineservice/attachList?tablename='+tablename+'&parentid='+data.id
            });
        }
    });

    form.on('switch(status)', function(data){
        var selectIfKey = data.othis;
        var parentTr = selectIfKey.parents("tr");
        var parentTrIndex = parentTr.attr("data-index");
        var id = parentTr.find(('td:eq(1)')).text().trim();
        var state = 2;
        if(data.elem.checked){state = 1;}
        $.post(ctx+'/sys_admin/modules/setStatus', {ids: id, status: state}, function() {}, 'json');
    });

    $("#add").on('click',function(){
        layer.open({
            type: 2,
            area: ['90%', '90%'],
            fixed: false, //不固定
            maxmin: true,
            content: ctx+'/sys_admin/mineservice/form?moduleid='+moduleid+'&tablename='+tablename,
            btn: ['提交','接口同步', '重置','取消'],
            yes: function(index, layero){
                var iframeWin = layero.find('iframe')[0];
                iframeWin.contentWindow.table = tableIns;
                iframeWin.contentWindow.params = params;
                layero.find('iframe').contents().find('#submit-btn').click();
            },
            btn2: function(index, layero){
                var iframeWin = layero.find('iframe')[0];
                iframeWin.contentWindow.table = tableIns;
                layero.find('iframe').contents().find('#interface').click();
                return false;
            },
            btn3: function(index, layero){
                var iframeWin = layero.find('iframe')[0];
                iframeWin.contentWindow.table = tableIns;
                layero.find('iframe').contents().find('#reset-btn').click();
                return false;
            },
            btn4: function(index, layero){
                var index = layer.getFrameIndex(window.name);
                layer.close(index);
            }
        });
    });

    form.on('submit(serach_form)', function (data) {
        table.reload('modulestable', {
            method : 'post',
            where: data.field,
            page: {
                curr : 1 //重新从第 1 页开始
            }
        });
        params['field'] = data.field;
        return false;
    });

    //导入功能
    $("#import").on('click',function(){
        parent.layer.open({
            type: 2,
            area: ['800px', '650px'],
            fixed: false, //不固定
            maxmin: true,
            content: ctx+'/sys_admin/mineservice/importForm?moduleid='+moduleid+'&tablename='+tablename,
            end:function(){
                tableIns.reload({});
            }
        });
    })

    //导出功能
    $("#export").on('click',function(){
        window.open(ctx+'/sys_admin/mineservice/exportExcel?moduleid='+moduleid+'&tablename='+tablename+'&type=1'+"&params="+JSON.stringify(params['field']));
    })

    //导入功能
    $("#delAll").on('click',function(){
        var checkStatus = table.checkStatus("modulestable");
        if(checkStatus.data.length>0){
            var datas = checkStatus.data;
            var ids = "";
            for (let i = 0; i < datas.length; i++) {
                var data = datas[i];
                if(data.createuser!=userid){
                    layer.open({
                        skin:'layui-layer-success',
                        title:'提示',
                        content:'存在非本人数据不能操作！',
                    });
                    return ;
                }
                if(ids.length>0){
                    ids += ','+checkStatus.data[i].id;
                }else{
                    ids += checkStatus.data[i].id;
                }
            }
            layer.confirm('确定删除行么？', function(index){
                $.post(ctx+'/sys_admin/mineservice/delete', {"tablename":tablename, "ids":ids}, function(result) {
                    if (result.success) {
                        layer.open({
                            skin:'layui-layer-success',
                            title:'提示',
                            content:'删除成功！',
                            yes:function(idx, layero){
                                tableIns.reload({});
                                layer.close(index);
                                layer.close(idx);
                            }
                        });
                        //obj.del();
                    } else {
                        layer.msg(result.msg);
                    }
                }, 'json');
            });
        }else{
            layer.msg('请选择一条数据！', {offset: '15px', icon: 2});
            return ;
        }
    })
});

function getFields() {
    var fields = new Array();
    fields.push( {type:'checkbox',fixed: 'left'});
    fields.push({type: 'numbers',fixed: 'left', totalRowText: '合计'});
    fields.push({field: 'id', title: 'ID',fixed: 'left', align:'center',width:180, hide:true});
    $.ajax({
        type: "POST",
        url: ctx+'/sys_admin/mineservice/showColumns',
        data: {'moduleid':moduleid},
        async:false,
        success: function(data){
            $.each(data, function(i, column){
                var width = 200;
                var type = column.column_type;
                var fd = {field: column.column_name, title: column.column_comment, align:'center'};
                if (i < data.length - 1) {
                    if (i == 0) {
                        fd['fixed'] = 'left';
                    }
                }
                if (type == 'text' || type == 'longtext') {
                    width = 500;
                }
                if (type == 'sex') {
                    fd['templet'] = function(d){
                        if (d[column.column_name] == 1) {
                            return '男';
                        } else {
                            return '女';
                        }
                    };
                }
                if (type == 'yesorno') {
                    fd['templet'] = function(d){
                        if (d[column.column_name] == 1) {
                            return '是';
                        } else {
                            return '否';
                        }
                    };
                }
                if (type == 'file') {
                    fd['templet'] = function(d){
                        //return d[column.column_name].split("@")[0] ;
                        if(d[column.column_name]==null){
                            return"";
                        }else{
                            return '<a href="javascript:void(0)" Onclick="preview(\'' +d[column.column_name].split("@")[1]+'\')">'+d[column.column_name].split("@")[0]+'</a>';
                        }
                    };
                }
                if (type == 'int' || type == 'double') {
                    fd['totalRow'] = true;
                }
                fd['width'] = width;
                fields.push(fd);
            });
        }
    });
    fields.push({field: 'username', title: '创建人', align:'center',width:180});
    fields.push({field: 'createdate', title: '创建时间', align:'center',width:180});
    fields.push({title: '操作', width: 250, fixed: 'right', align:'center',toolbar: '#toolbar'});
    return fields;
}

function preview(path) {
    var fileUrl = ctx+path;
    var url = "http://116.63.43.8:8012/onlinePreview?url=" + encodeURIComponent(fileUrl);
    var winHeight = window.document.documentElement.clientHeight-10;
    window.open(url,"_blank", "height=" + winHeight + ", top=30, left=40, toolbar=no, menubar=no, scrollbars=yes, resizable=yes ");
}